import axios from 'axios'

// 创建axios实例
const api = axios.create({
  baseURL: '/api', // 后端API基础路径
  timeout: 10000,
  withCredentials: true // 支持session
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => {
    console.log('API响应:', response.data)
    return response.data
  },
  error => {
    console.error('API请求错误:', error)
    console.error('错误详情:', {
      status: error.response?.status,
      statusText: error.response?.statusText,
      data: error.response?.data,
      config: {
        url: error.config?.url,
        method: error.config?.method,
        data: error.config?.data
      }
    })
    
    // 如果后端返回了错误响应，提取错误信息
    if (error.response && error.response.data) {
      return Promise.reject(error.response.data)
    }
    
    // 如果是网络错误或其他错误
    return Promise.reject({
      code: error.response?.status || 500,
      message: error.message || '网络请求失败',
      data: null
    })
  }
)

// 配送员接口类型定义
export interface Courier {
  id?: number
  userId?: number
  jobNumber: string
  status: 'active' | 'inactive' | 'suspended'
  area: string
  deliveryCount?: number
  entryDate?: string
  createDate?: string
  updateDate?: string
  name: string
  phone: string
  email?: string
  user?: {
    userId: number
    username: string
    phone: string
    email: string
    roles: string
    status: number
    createdAt: string
    updatedAt: string
  }
}

// 添加配送员请求参数
export interface AddCourierRequest {
  name: string
  phone: string
  email?: string
  area: string
  status?: 'active' | 'inactive' | 'suspended'
  jobNumber?: string
}

// 修改配送员请求参数
export interface UpdateCourierRequest {
  name?: string
  phone?: string
  email?: string
  area?: string
  status?: 'active' | 'inactive' | 'suspended'
  jobNumber?: string
  deliveryCount?: number
  entryDate?: string
}

// API响应格式
export interface ApiResponse<T = any> {
  code: number
  message: string
  data: T
}

// 可接订单类型定义
export interface AvailableOrder {
  deliveryOrderId: number
  orderNumber: string
  userId: number
  senderName: string
  senderPhone: string
  senderAddress: string
  receiverName: string
  receiverPhone: string
  receiverAddress: string
  itemVolume: number
  itemWeight: number
  itemType: string
  insuredValue: number
  baseFee: number
  weightFee: number
  serviceFee: number
  insuranceFee: number
  totalFee: number
  remark: string
  delivererId: number | null
  paymentMethod: string
  orderStatus: number
  createdAt: string
  updatedAt: string
}

// 可接订单列表响应
export interface AvailableOrdersResponse {
  list: AvailableOrder[]
  total: number
  pageNum: number
  pageSize: number
}

// 接单请求参数
export interface AcceptOrderRequest {
  orderId: number
  remark?: string
}

// 接单响应
export interface AcceptOrderResponse {
  orderId: number
  orderNumber: string
  assignmentId: number
  assignedAt: string
}

// 配送记录类型
export interface DeliveryAssignment {
  assignmentId: number
  orderId: number
  courierId: number
  status: number // 配送状态：0-待揽件，1-待发货，2-运输中，3-已送达，4-已签收
  assignedAt: string
  completedAt: string | null
  remark: string
  createdAt: string
  updatedAt: string
  orderNumber: string
  senderName: string
  receiverName: string
  receiverAddress: string
}

// 配送记录列表响应
export interface DeliveryAssignmentsResponse {
  list: DeliveryAssignment[]
  total: number
  pageNum: number
  pageSize: number
}

/**
 * 获取所有配送员
 */
export function getCouriers(): Promise<ApiResponse<Courier[]>> {
  return api({
    url: '/admin/couriers',
    method: 'get'
  })
}

/**
 * 添加配送员
 */
export function addCourier(data: AddCourierRequest): Promise<ApiResponse<string>> {
  return api({
    url: '/admin/couriers',
    method: 'post',
    data
  })
}

/**
 * 修改配送员
 */
export function updateCourier(id: number, data: UpdateCourierRequest): Promise<ApiResponse<string>> {
  return api({
    url: `/admin/couriers/${id}`,
    method: 'put',
    data
  })
}

/**
 * 删除配送员
 */
export function deleteCourier(id: number): Promise<ApiResponse<string>> {
  return api({
    url: `/admin/couriers/${id}`,
    method: 'delete'
  })
}

/**
 * 获取可接订单列表
 */
export function getAvailableOrders(pageNum: number = 1, pageSize: number = 10): Promise<ApiResponse<AvailableOrdersResponse>> {
  return api({
    url: '/courier/available-orders',
    method: 'get',
    params: {
      pageNum,
      pageSize
    }
  })
}

/**
 * 配送员接单
 */
export function acceptOrder(data: AcceptOrderRequest): Promise<ApiResponse<AcceptOrderResponse>> {
  console.log('发送接单请求:', data)
  
  // 使用URLSearchParams来发送application/x-www-form-urlencoded数据
  const params = new URLSearchParams()
  params.append('orderId', data.orderId.toString())
  if (data.remark) {
    params.append('remark', data.remark)
  }
  
  console.log('请求参数:', params.toString())
  
  return api({
    url: '/courier/accept-order',
    method: 'post',
    data: params,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  })
}

/**
 * 配送员接单 (备用方法，使用JSON格式)
 */
export function acceptOrderJson(data: AcceptOrderRequest): Promise<ApiResponse<AcceptOrderResponse>> {
  console.log('发送接单请求(JSON格式):', data)
  
  return api({
    url: '/courier/accept-order',
    method: 'post',
    data: {
      orderId: data.orderId,
      remark: data.remark || ''
    },
    headers: {
      'Content-Type': 'application/json'
    }
  })
}

/**
 * 获取我的配送记录
 */
export function getMyAssignments(pageNum: number = 1, pageSize: number = 10): Promise<ApiResponse<DeliveryAssignmentsResponse>> {
  return api({
    url: '/courier/my-assignments',
    method: 'get',
    params: {
      pageNum,
      pageSize
    }
  })
}

/**
 * 获取订单详情
 */
export function getOrderDetails(orderId: number): Promise<ApiResponse<AvailableOrder>> {
  return api({
    url: `/courier/order-details/${orderId}`,
    method: 'get'
  })
}

/**
 * 更新配送状态
 */
export function updateDeliveryStatus(assignmentId: number, status: number, remark?: string): Promise<ApiResponse<any>> {
  console.log('更新配送状态:', { assignmentId, status, remark })
  
  const params = new URLSearchParams()
  params.append('assignmentId', assignmentId.toString())
  params.append('status', status.toString())
  if (remark) {
    params.append('remark', remark)
  }
  
  return api({
    url: '/delivery/update-status',  // 修改为正确的路径
    method: 'post',
    data: params,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  })
}

/**
 * 开始发货
 */
export function startDelivery(assignmentId: number, remark?: string): Promise<ApiResponse<any>> {
  return updateDeliveryStatus(assignmentId, 1, remark)
}

/**
 * 标记送达
 */
export function markDelivered(assignmentId: number, remark?: string): Promise<ApiResponse<any>> {
  return updateDeliveryStatus(assignmentId, 2, remark)
}

/**
 * 确认签收
 */
export function markSigned(assignmentId: number, remark?: string): Promise<ApiResponse<any>> {
  return updateDeliveryStatus(assignmentId, 3, remark)
}

/**
 * 完成配送 (兼容旧接口)
 */
export function completeDelivery(assignmentId: number, remark?: string): Promise<ApiResponse<any>> {
  return updateDeliveryStatus(assignmentId, 3, remark)
}

// 物流轨迹相关类型定义
export interface TrackRecord {
  timestamp: string
  status: number
  description: string
  location: {
    longitude: number
    latitude: number
    address: string
  }
  operator: string
  remark: string | null
}

export interface TrackData {
  id: string
  deliveryOrderId: number
  orderNumber: string
  trackRecords: TrackRecord[]
  createdAt: string
  updatedAt: string
}

export interface AddTrackRequest {
  location: string  // 保留地址用于显示
  latitude: number  // 添加纬度
  longitude: number // 添加经度
  remark?: string
  status: number
}

export function addTrack(orderId: number, data: any): Promise<ApiResponse<null>> {
  // 构造符合后端 DeliveryTrack.TrackRecord 结构的数据
  const trackRecord = {
    location: {
      address: data.location,
      latitude: data.latitude,
      longitude: data.longitude
    },
    status: data.status,
    description: data.description || getStatusDescription(data.status),
    timestamp: new Date().toISOString(),
    operator: data.operator || '配送员',
    remark: data.remark || null
  }
  
  console.log('发送轨迹数据:', trackRecord)
  
  return api({
    url: `/deliveryTrack/addRecord?deliveryOrderId=${orderId}`,  // 修改路径
    method: 'post',
    data: trackRecord,
    headers: {
      'Content-Type': 'application/json'
    }
  })
}

// 添加状态描述映射函数
function getStatusDescription(status: number): string {
  const statusMap: { [key: number]: string } = {
    1: '已下单',
    2: '待揽件',
    3: '已揽件',
    4: '运输中',
    5: '已送达',
    6: '已签收'
  }
  return statusMap[status] || '未知状态'
}

// 配送员仪表盘数据类型
export interface CourierDashboardData {
  todayCompleted: number // 今日配送完成的订单数
  inProgress: number // 正在进行中的订单数
  availableOrders: number // 可接的订单数
  todayDelivered: number // 今日送达的订单数
  currentTasks: CurrentTask[] // 当前配送任务列表
  summary: {
    totalToday: number // 今日总处理订单数
    workload: number // 当前工作负荷
  }
}

// 当前配送任务类型
export interface CurrentTask {
  assignmentId: number // 配送任务ID
  orderId: number // 订单ID
  orderNumber: string // 订单编号
  senderName: string // 寄件人姓名
  receiverName: string // 收件人姓名
  receiverAddress: string // 收件地址
  assignedAt: string // 分配时间
  status: number // 配送任务状态
  orderStatus: number // 订单状态
  remark?: string // 备注
}

/**
 * 获取配送员仪表盘数据
 */
export function getCourierDashboard(): Promise<ApiResponse<CourierDashboardData>> {
  console.log('获取配送员仪表盘数据')
  return api({
    url: '/courier/dashboard',
    method: 'get'
  })
}

/**
 * 配送员API统一导出对象
 */
export const courierApi = {
  getCouriers,
  addCourier,
  updateCourier,
  deleteCourier,
  // 订单接口
  getAvailableOrders,
  acceptOrder,
  acceptOrderJson,
  getMyAssignments,
  getOrderDetails,
  // 配送状态更新接口
  updateDeliveryStatus,
  startDelivery,
  markDelivered,
  markSigned,
  completeDelivery,
  // 物流轨迹接口
  addTrack,
  // 仪表盘接口
  getCourierDashboard
}

// 删除这个重复的函数定义
// export function getTrack(orderId: number): Promise<ApiResponse<TrackData>> {
//   console.log('获取物流轨迹:', { orderId })
//   return api({
//     url: `/courier/track/${orderId}`,
//     method: 'get'
//   })
// }